package com.hqy.oauth.controller;

import com.hqy.oauth.aspect.FailRequestLimit;
import com.hqy.oauth.enums.ReturnCodeEnum;
import com.hqy.oauth.expection.BusinessException;
import com.hqy.oauth.service.LoginService;
import com.hqy.oauth.util.IpUtil;
import com.hqy.oauth.dto.AuthToken;
import com.hqy.oauth.dto.GmallResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 自定义的登录接口
 */
@RestController
@RequestMapping(value = "/api/oauth")
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    private static final String LOG_PREFIX = "[AUTH-SERVICE][LoginController]";

    @Autowired
    private LoginService loginService;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //这个手机和网页端的不同，为什么不同我要了解一下，然后看看海哥那边是怎么处理的 todo
    @PostMapping("/login")
    @FailRequestLimit(maxRetries = 4, timeWindow = 2, errorCode = "1111", errorMessage = "失败次数过多，请稍后重试")
    public GmallResult<Object> login(String username, String password, HttpServletRequest request){
        try {
            AuthToken login = loginService.login(username, password);
            String ipAddress = IpUtil.getIpAddress(request);
//            redisTemplate.opsForValue().set(ipAddress,login.getAccessToken());
            stringRedisTemplate.opsForValue().set(ipAddress,login.getAccessToken(),30, TimeUnit.MINUTES);
            return GmallResult.ok(login);
        } catch (BusinessException e) {
            logger.error("{} 业务异常: {}", LOG_PREFIX, e.getMessage());
            return GmallResult.fail(e.getReturnCodeEnum().getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("{} 系统异常: {}", LOG_PREFIX, e.getMessage(), e);
            return GmallResult.fail(ReturnCodeEnum.SYSTEM_ERROR.getCode(), "系统繁忙，请稍后再试");
        }
    }
}
